/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       timer.cpp
 * Author:     karooolek
 * Created on: 2009-01-06
 *
 **********************************************************************************************************************/

#include "timer.h"

namespace mGameEngine
{

uint64 Timer::_clock()
{
#ifdef WIN32
    LARGE_INTEGER c, f;
    QueryPerformanceCounter(&c);
    QueryPerformanceFrequency(&f);
    return 1000000 * c.QuadPart / f.QuadPart;
#else
    timeval t;
    gettimeofday(&t, 0);
    return 1000000 * t.tv_sec + t.tv_usec;
#endif
}

Timer::Timer()
{
    reset();
    start();
}

Timer::Timer(float time, bool running)
{
    setTime(time);

    if(running)
    {
        start();
    }
    else
    {
        stop();
    }
}

Timer::~Timer()
{
}

bool Timer::isRunning() const
{
    return _stop == (uint64)-1;
}

void Timer::start()
{
    stop();
    _start += _clock() - _stop;
    _stop = uint64(-1);
}

void Timer::stop()
{
    if(isRunning())
    {
        _stop = _clock();
    }
}

void Timer::reset()
{
    _start = isRunning() ? _clock() : _stop;
}

float Timer::getTime() const
{
    return float((isRunning() ? _clock() : _stop) - _start) * 0.000001f;
}

void Timer::setTime(float sec)
{
    _start = uint64((isRunning() ? _clock() : _stop) - sec * 1000000.0f);
}

}
